import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Radio, Switch, Form, Button, message, Icon, Modal, Checkbox } from 'antd';
import { messages, deepCopy } from 'share/common';
import Priority from 'components/template/priority/priority';
import 'styles/finance-setting/audit-basis-config/audit-basis-config.scss';
import auditBasisService from 'containers/finance-setting/audit-basis-config/audit-basis-service';
import { permission } from '../permisson';
import Table from "components/table";
import errorMessage from 'share/errorMessage';
import EditSuitStaff from './edit-suit-staff'

const { Group } = Radio;

@connect(mapStateToProps)
@permission
class NewAuditBasisConfig extends Component {

  static PropTypes = {};

  radioChild = [
    { name: messages('common.yes')/*是*/, value: true },
    { name: messages('common.no')/*否*/, value: false }
  ];

  billOperateOptions = [
    { label: messages('common.pass')/*通过*/, value: 'pass' },
    { label: messages('common.reject')/*驳回*/, value: 'reject' },
    { label: messages('expense-14.key497')/*从发票袋移除*/, value: 'removeFromBag' },
    { label: messages('common.print')/*打印*/, value: 'print' },
    { label: messages('expense-14.key20')/*暂挂*/, value: 'hangUp' },
    { label: messages('expense-14.key21')/*通知/暂挂*/, value: 'noticeBtn' },
    { label: messages('expense-14.key22')/*自动审核*/, value: 'autoAudit' },
    { label: messages('expense-14.key23')/*查验发票*/, value: 'auditCheck' },
    { label: messages('expense-14.key24')/*打印凭证*/, value: 'print-certificate' },
    { label: messages('expense-14.key25')/*加签*/, value: 'additional' },
    { label: messages('expense-14.key26')/*转交*/, value: 'approveTransfer' }
  ];

  corpOperateOptions = [
    { label: messages('common.pass')/*通过*/, value: 'pass' },
    { label: messages('common.reject')/*驳回*/, value: 'reject' },
    { label: messages('common.print')/*打印*/, value: 'print' },
    { label: messages('expense-14.key20')/*暂挂*/, value: 'hangUp' },
    { label: messages('expense-14.key21')/*通知/暂挂*/, value: 'noticeBtn' },
    { label: messages('expense-14.key22')/*自动审核*/, value: 'autoAudit' },
    { label: messages('expense-14.key23')/*查验发票*/, value: 'auditCheck' },
    { label: messages('expense-14.key24')/*打印凭证*/, value: 'print-certificate' },
    { label: messages('expense-14.key25')/*加签*/, value: 'additional' },
    { label: messages('expense-14.key26')/*转交*/, value: 'approveTransfer' }
  ];

  bagOperateOptions = [
    { label: messages('expense-14.key22')/*自动审核*/, value: 'autoAudit' },
    { label: messages('common.pass')/*通过*/, value: 'pass' },
    { label: messages('common.reject')/*驳回*/, value: 'reject' },
    { label: messages('expense-14.key23')/*查验发票*/, value: 'check-invoice' },
    { label: messages('expense-14.key21')/*通知/暂挂*/, value: 'noticeBtn' },
    { label: messages('expense-14.key25')/*加签*/, value: 'additional' }
  ];

  billOperateDefault = ['removeFromBag', 'hangUp', 'noticeBtn', 'autoAudit', 'auditCheck', 'print-certificate', 'additional', 'approveTransfer'];

  corpOperateDefault = ['hangUp', 'noticeBtn', 'autoAudit', 'auditCheck', 'print-certificate', 'additional', 'approveTransfer'];

  bagOperateDefault = ['check-invoice', 'noticeBtn', 'additional'];

  infoStyle = {
    color: '#4B8DFF',
    textAlign: 'right',
    fontSize: '12px',
    top: '-2px',
    position: 'relative',
    marginLeft: '3px',
    fontWeight: 700
  };

  titleStyle = {
    height: '40px',
    backgroundColor: 'rgb(247, 248, 250)',
    color: '#666666',
    lineHeight: '40px',
    fontSize: '16px',
    margin: '0px -32px 20px',
    fontWeight: '500',
    padding: '0px 32px',
    borderRadius: '5px 5px 0 0'
  };

  handleRenderView = value => {
    let temp = value.split(',');
    return temp.map(item => <div style={{ whiteSpace: 'normal' }}>{item}</div>)
  };

  viewColumns = [
    { title: messages('expense-14.key325')/*工作流内是否有人工审核节点*/, dataIndex: 'insertWork', render: value => this.handleRenderView(value), width: 210 },
    { title: messages('expense-14.key326')/*工作流外是否有人工审核节点*/, dataIndex: 'outsideWork', render: value => this.handleRenderView(value), width: 210 },
    { title: messages('expense-14.key327')/*需要配置*/, dataIndex: 'enableConfig', render: value => this.handleRenderView(value) }
  ];

  viewData = [
    { insertWork: `Y,${messages('expense-14.key328')/*使用报销单审核页面*/}`, outsideWork: `Y,${messages('expense-14.key328')/*使用报销单审核页面*/}`, enableConfig: messages('expense-14.key329')/*无配置，不支持本模式*/ },
    { insertWork: 'N', outsideWork: `Y,${messages('expense-14.key328')/*使用报销单审核页面*/}`, enableConfig: messages('expense-14.key330')/*报销单待审核不显示审批通过的发票袋：否*/ },
    {
      insertWork: `Y,${messages('expense-14.key328')/*使用报销单审核页面*/}`, outsideWork: 'N',
      enableConfig: `${messages('expense-14.key330')/*报销单待审核不显示审批通过的发票袋：否*/},${messages('expense-14.key331')/*报销单审批通过后，是否自动审核通过：是（在特性配置文件菜单进行配置。注意：无论报销单是否关联发票袋，该配置均会生效）*/}`
    },
    { insertWork: `Y,${messages('expense-14.key328')/*使用报销单审核页面*/}`, outsideWork: `Y,${messages('expense-14.key332')/*使用发票袋审核页面*/}`, enableConfig: messages('expense-14.key333')/*报销单待审核不显示审批通过的发票袋：是*/ },
    { insertWork: 'N', outsideWork: `Y,${messages('expense-14.key332')/*使用发票袋审核页面*/}`, enableConfig: messages('expense-14.key330')/*报销单待审核不显示审批通过的发票袋：否*/ }
  ];

  viewModal = () => {
    Modal.info({
      content: <div>
        <h3 style={this.titleStyle}>{messages('expense-14.key334')/*配置说明*/}</h3>
        <Table columns={this.viewColumns} dataSource={this.viewData} pagination={false}/>
      </div>,
      className: 'audit-view-info',
      width: 800,
      maskClosable: true
    })
  };

  state = {
    formList: {
      enabled: {
        component: Switch,
        name: messages('common.column.status')/*状态*/,
        initData: true,
        valuePropName: 'checked'
      },
      reviewExpBeforeReceiveTitle: {
        isTitle: true,
        child: messages('expense-14.key335')/*报销单审核设置*/,
        component: 'h3',
        params: { className: 'sub-title' },
      },
      reviewExpBeforeReceive: {
        child: this.radioChild.map(item => <Radio value={item.value}>{item.name}</Radio>),
        extra: messages('expense-14.key336')/*配置为“是”，则未收单单据不会显示在待审核列表中（免打印报销单除外）*/,
        component: Group,
        initData: false,
        name: messages('expense-14.key337')/*收单后才可审核*/
      },
      pendingAuditFilterBag: {
        child: this.radioChild.map(item => <Radio value={item.value}>{item.name}</Radio>),
        extra: messages('expense-14.key340')/*配置为“是”，则表示报销单待审核列表，不显示审批通过且关联发票袋的报销单*/,
        component: Group,
        initData: false,
        name: (
          <span>
            {messages('expense-14.key341')/*报销单待审核不显示审批通过的发票袋*/}
            <Icon type="info-circle-o" style={{ marginLeft: 5 }} onClick={this.viewModal}/>
          </span>
        )
      },
      rejectWithCondition: {
        child: this.radioChild.map(item => <Radio value={item.value}>{item.name}</Radio>),
        extra: messages('expense-14.key342')/*配置为“是”，则报销单审核驳回时，若未命中信用事件则系统会有二次确认弹窗*/,
        component: Group,
        initData: false,
        name: messages('expense-14.key343')/*驳回时未命中信用事件则给予提示*/
      },
      billReviewMoreOperateList: {
        extra: (<div>
          {messages('expense-14.key344')/*勾选上的按钮，在单据审核中将收起到更多操作中，未勾选的按钮将平铺在外面*/} <br/>
          {messages('expense-14.key345')/*若单据原本就不显示该按钮，则无论如何配置都不会显示*/}
        </div>),
        component: Checkbox.Group,
        initData: this.billOperateDefault,
        defaultData: this.billOperateDefault.map((key, index) =>
          this.billOperateOptions.filter(item => item.value === key)[0].label +
          (index === this.billOperateDefault.length - 1 ? '' : '、')
        ),
        name: messages('expense-14.key346')/*单据审核更多操作*/,
        params: {
          options: this.billOperateOptions
        }
      },
      bagReviewMoreOperateList: {
        extra: (<div>
          {messages('expense-14.key347')/*勾选上的按钮，在发票袋审核中将收起到更多操作中，未勾选的按钮将平铺在外面*/} <br/>
          {messages('expense-14.key345')/*若单据原本就不显示该按钮，则无论如何配置都不会显示*/}
        </div>),
        component: Checkbox.Group,
        initData: this.bagOperateDefault,
        defaultData: this.bagOperateDefault.map((key,index) =>
          this.bagOperateOptions.filter(item => item.value === key)[0].label +
          (index === this.bagOperateDefault.length - 1 ? '' : '、')
        ),
        name: messages('expense-14.key348')/*发票袋审核更多操作*/,
        params: {
          options: this.bagOperateOptions
        }
      },
      reviewCorporateBeforeReceiveTitle: {
        isTitle: true,
        child: messages('expense-14.key508')/*对公支付单审核设置*/,
        component: 'h3',
        params: { className: 'sub-title' }
      },
      corpReviewExpBeforeReceive: {
        child: this.radioChild.map(item => <Radio value={item.value}>{item.name}</Radio>),
        extra: messages('expense-14.key509')/*配置为“是”，则未收单单据不会显示在待审核列表中（免打印对公支付单除外）*/,
        component: Group,
        initData: false,
        name: messages('expense-14.key337')/*收单后才可审核*/
      },
      corpBillReviewMoreOperateList: {
        extra: (<div>
          {messages('expense-14.key344')/*勾选上的按钮，在单据审核中将收起到更多操作中，未勾选的按钮将平铺在外面*/} <br/>
          {messages('expense-14.key345')/*若单据原本就不显示该按钮，则无论如何配置都不会显示*/}
        </div>),
        component: Checkbox.Group,
        initData: this.corpOperateDefault,
        defaultData: this.corpOperateDefault.map((key, index) =>
          this.corpOperateOptions.filter(item => item.value === key)[0].label +
          (index === this.corpOperateDefault.length - 1 ? '' : '、')
        ),
        name: messages('expense-14.key346')/*单据审核更多操作*/,
        params: {
          options: this.corpOperateOptions
        }
      },
      reviewLoanBeforeReceiveTitle: {
        isTitle: true,
        child: messages('expense-14.key349')/*借款单审核设置*/,
        component: 'h3',
        params: { className: 'sub-title' }
      },
      reviewLoanBeforeReceive: {
        child: this.radioChild.map(item => <Radio value={item.value}>{item.name}</Radio>),
        extra: messages('expense-14.key350')/*配置为“是”，则未收单单据不会显示在待审核列表中*/,
        component: Group,
        initData: false,
        name: messages('expense-14.key337')/*收单后才可审核*/
      },
      loanAmountAlter: {
        child: this.radioChild.map(item => <Radio value={item.value}>{item.name}</Radio>),
        extra: messages('expense-14.key520')/*配置为“是”，则审核编辑时可以改小借款金额*/,
        component: Group,
        initData: false,
        name: messages('expense-14.key521')/*借款金额修改*/
      },
      reviewEditTitle: {
        isTitle: true,
        child: messages('expense-14.key351')/*审核编辑设置*/,
        component: 'h3',
        params: { className: 'sub-title' }
      },
      reviewEditSuitStaff:{},
      reviewEditEnable: {
        child: this.radioChild.map(item => <Radio value={item.value}>{item.name}</Radio>),
        extra: messages('expense-14.key522')/*配置为“是”，则可修改报销单、借款单以及对公支付单的单据头信息、记账日期、付款行信息、费用信息*/,
        component: Group,
        initData: false,
        name: messages('expense-14.key353')/*修改单据信息*/
      },
      reviewEditAmountIncreasable: {
        child: this.radioChild.map(item => <Radio value={item.value}>{item.name}</Radio>),
        extra: messages('expense-14.key354')/*配置为“是”，则核定金额允许修改为大于原金额*/,
        component: Group,
        initData: false,
        name: messages('expense-14.key355')/*核定金额改大*/
      },
      updateWriteOff: {
        child: this.radioChild.map(item => <Radio value={item.value}>{item.name}</Radio>),
        extra: messages('expense-14.key356')/*配置为“是”，则付款行上显示“冲借款”入口，可修改付款行相关的核销记录*/,
        component: Group,
        initData: false,
        name: messages('expense-14.key357')/*修改核销记录*/
      },
      expenseBatchReject: {
        child: this.radioChild.map(item => <Radio value={item.value}>{item.name}</Radio>),
        extra: messages('expense-14.key338')/*配置为“是”，则允许财务以费用维度进行驳回*/,
        component: Group,
        initData: false,
        name: messages('expense-14.key339')/*费用批量驳回*/
      },
      reviewReceiveTitle: {
        isTitle: true,
        child: messages('expense-14.key358')/*收单设置*/,
        component: 'h3',
        params: { className: 'sub-title' }
      },
      receiveWithAudit: {
        child: this.radioChild.map(item => <Radio value={item.value}>{item.name}</Radio>),
        extra: messages('expense-14.key359')/*配置为“是”，则扫码收单页面显示“收单并审核通过”按钮*/,
        component: Group,
        initData: false,
        name: messages('expense-14.key360')/*扫码收单页面支持审核*/
      },
    },
    priority: void 0,
    submitLoading: false
  };

  componentWillMount() {
    this.handleInit();
  }

  handleInit = () => {
    let { formList, priority = {} } = this.state;
    const { params, params: { levelCode, levelOrgId, levelOrgName, distLevelOrgIds, baseConfigId, companyInfos } } = this.props;

    if (!baseConfigId) {
      priority = {
        levelCode: 'TENANT',
        levelOrgId: this.props.currentMenuPermission.currentMenuPermission.tenantId
      };
      this.setState({ priority });
      return;
    }

    Object.keys(formList)
      .map(item => {
        if (params[item] !== null && params[item] !== void 0) {
          formList[item].initData = params[item];
        }
      });
    priority.distribution = {};
    distLevelOrgIds && (priority.distribution.companies = companyInfos);
    priority = { ...priority, levelCode, levelOrgId, levelOrgName };
    this.setState({ formList, priority });
  };

  handleSubmit = e => {
    e.preventDefault();
    let distLevelOrgIds = [];
    const { priority, priority: { distribution } } = this.state;
    const { params } = this.props;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        if (!priority || !priority.levelCode) {
          message.error(messages('expense-12.key153')/*请选择所属组织*/);
          return;
        }
        if(priority && (priority.levelCode === 'TENANT') && priority.distribution && priority.distribution.companies &&
          !priority.distribution.companies.length) {
          message.error(messages('expense-12.key150')/*请选择启用公司*/);
          return;
        }
        this.setState({ submitLoading: true });
        distribution && distribution.companies && (distLevelOrgIds = distribution.companies.map(item => item.id));
        delete priority.distribution;
        let reviewEditSuitStaff = deepCopy(values.reviewEditSuitStaff.reviewEditSuitStaff);
        reviewEditSuitStaff = reviewEditSuitStaff ? reviewEditSuitStaff.map(item => item.id) : null;
        auditBasisService.saveAuditBasisConfig({ ...params, ...values, ...priority, distLevelOrgIds, reviewEditSuitStaff })
          .then(() => {
            message.success(messages('common.save.success',{arg1: ''})/*{arg1} 保存成功*/);
            this.props.close(true);
          })
          .finally(() => {
            this.setState({ submitLoading: false });
          });
      }
    });
  };

  handleCancel = () => {
    this.props.close(false);
  };

  handlePriority = (priority) => {
    this.setState({ priority: priority || {} });
    this.props.form.setFieldsValue({
      reviewEditSuitStaff: {
        staffType: 'ALL',
        reviewEditSuitStaff: []
      }
    })
  };

  fenderForm = () => {
    const { formList, submitLoading, priority } = this.state;
    const { form: { getFieldDecorator }, mode, params: { readOnly, baseConfigId, reviewEditSuitStaffDTOList } } = this.props;
    const formItemLayout = { labelCol: { span: 7 }, wrapperCol: { span: 15, offset: 1 } };
    if (mode === 'rule') {
      delete formList.enabled;
    }

    //增加审核编辑适用人员配置项
    formList.reviewEditSuitStaff = {
      extra:messages('expense-14.key511')/*配置为\"部分\"人员组，则仅人员组中的用户适用\"审核编辑设置\"中的规则*/,
      component: <EditSuitStaff
        priority={priority}
      />,
      name: messages('expense-14.key512')/*审核编辑适用人员*/,
      initData: baseConfigId ? {
        staffType: (reviewEditSuitStaffDTOList || []).length ? 'PART' : 'ALL',
        reviewEditSuitStaff: reviewEditSuitStaffDTOList
      } : {
        staffType: 'ALL',
        reviewEditSuitStaff: []
      }
    };

    const formArray = Object.keys(formList)
      .map(item => {
        const middleForm = formList[item];
        let Element;
        let { name, child, params = {}, require, component, extra, isTitle } = middleForm;
        params.disabled = mode === 'rule' || readOnly || this.isReadOnly();
        if (item !== 'reviewEditSuitStaff') {
          if (mode === 'rule' && !isTitle) {
            component = 'span';
            child = middleForm.defaultData || messages('common.no')/*否*/;
          }
          Element = React.createElement(component, params, child);
          if (isTitle) {
            return Element;
          }
        } else {
          Element = middleForm.component;
        }
        return (
          <Form.Item  {...formItemLayout} extra={extra} label={name}>
            {
              getFieldDecorator(item, {
                rules: [{
                  required: !!require,
                  message: messages('expense-14.key174')/*请输入temp2*/ + item.name
                }],
                initialValue: formList[item].initData,
                valuePropName: formList[item].valuePropName || 'value'
              })(Element)
            }
          </Form.Item>
        );
      });

    mode === 'basis' && formArray.splice(1, 0, (
      <Priority
        top={'TENANT'}
        single={false}
        disabled={readOnly || !!baseConfigId && priority.levelCode === 'COMPANY'}
        onChange={this.handlePriority}
        required
        showCompany
        disabledTop={!!baseConfigId}
        defaultValue={priority}
        formItemLayout={formItemLayout}
      />));

    return (
      <Form className='new-form' onSubmit={this.handleSubmit}>
        {
          formArray
        }
        <div className="slide-footer">
          {mode === 'basis' &&
          <Button
            disabled={readOnly || this.isReadOnly()}
            type="primary"
            htmlType="submit"
            loading={submitLoading}
          >
            {messages('common.save')/*保存*/}
          </Button>
          }
          <Button
            disabled={readOnly || this.isReadOnly()}
            onClick={this.handleCancel}
            className="new-audit-basis-cancel"
          >
            {messages('common.cancel')/*取消*/}
          </Button>
        </div>
      </Form>
    );

  };

  render() {
    return (
      <section className="new-audit-basis">
        {
          this.fenderForm()
        }
      </section>
    );
  }
}


function mapStateToProps(state) {
  return {
    currentMenuPermission: state.main.currentMenuPermission,
  };
}

const WrappedNewAuditBasisConfig = Form.create()(NewAuditBasisConfig);

export default WrappedNewAuditBasisConfig;
